package com.ggh.jinjilive.ui.mall.goods.affirm;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.ggh.jinjilive.BaseApplication;
import com.ggh.jinjilive.R;
import com.ggh.jinjilive.databinding.ActivityShoppingCarAffirmOrderBinding;
import com.ggh.jinjilive.listener.AddItemOnClickListener;
import com.ggh.jinjilive.mobile.CommonMobile;
import com.ggh.jinjilive.mobile.Pay.WeChatPayMobile;
import com.ggh.jinjilive.mobile.mall.goods.GoodsShopMobile;
import com.ggh.jinjilive.mobile.mall.goods.GoodsShopSPMobile;
import com.ggh.jinjilive.mobile.mall.goods.thegoods.TheGoodsAddressMobile;
import com.ggh.jinjilive.mobile.mall.shopping.ShopMessageMoblie;
import com.ggh.jinjilive.ui.BaseActivity;
import com.ggh.jinjilive.ui.mall.goods.affirm.adaoter.ShoppingCarAffirmAdapter;
import com.ggh.jinjilive.utils.ARouterUtils;
import com.ggh.jinjilive.utils.pay.PayUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Route(path = ARouterUtils.ShoppingCarAffirmActivity)
public class ShoppingCarAffirmActivity extends BaseActivity<ActivityShoppingCarAffirmOrderBinding> implements View.OnClickListener {
    //VM
    private AffirmOrderViewModel affirmOrderViewModel;
    //购物车传输过来的数据
    private List<ShopMessageMoblie> mShopMessageMoblieList;
    //确认订单适配器
    private ShoppingCarAffirmAdapter shoppingCarAffirmAdapter;
    //价格
    private double mPrice = 0.00;
    //数量
    private int mNumber = 0;
    //社区还是商城
    private int Cid = 0;
    @Override
    public void initCreate() {
        super.initCreate();
        ImmersionBar.with(this).init();
        BaseApplication.getInstance().getAppComponent().doInjectionMain(this);
        affirmOrderViewModel = new ViewModelProvider(this,viewModelFactory).get(AffirmOrderViewModel.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_shopping_car_affirm_order;
    }

    @Override
    public void initParam() {
        super.initParam();
        String shopping = getIntent().getStringExtra("shopping");
        if(!TextUtils.isEmpty(shopping)){
            List<ShopMessageMoblie> shopMessageMoblieList = new Gson().fromJson(shopping,new TypeToken<List<ShopMessageMoblie>>() {}.getType());
            mShopMessageMoblieList = new ArrayList<>();
            if(null != shopMessageMoblieList && shopMessageMoblieList.size() > 0){
                for (ShopMessageMoblie shopMessageMoblie : shopMessageMoblieList){
                    ShopMessageMoblie shopMessageMoblie1 = shopMessageMoblie;
                    List<GoodsShopSPMobile> goodsShopSPMobileList = new ArrayList<>();
                    for (GoodsShopSPMobile goodsShopSPMobile : shopMessageMoblie.getProduct()){
                        if(goodsShopSPMobile.isSelected()){
                            goodsShopSPMobileList.add(goodsShopSPMobile);
                        }
                    }
                    if(null != goodsShopSPMobileList && goodsShopSPMobileList.size() > 0){
                        shopMessageMoblie1.setProduct(goodsShopSPMobileList);
                        mShopMessageMoblieList.add(shopMessageMoblie1);
                    }
                }
            }

        }
    }

    @Override
    public void initView() {
        super.initView();
        setWhiteActionBarStyle("确认订单",true,true);
        //获取状态栏高度
        binding.llSpacing.setPadding(0, BarUtils.getStatusBarHeight(),0,0);


        shoppingCarAffirmAdapter = new ShoppingCarAffirmAdapter();
        shoppingCarAffirmAdapter.setAddItemOnClickListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                List<ShopMessageMoblie> shopMessageMoblieList = (List<ShopMessageMoblie>) mObject;
                if(null != shopMessageMoblieList){
                    /**
                     * 计算价格
                     */
                    calculatePrice(shopMessageMoblieList);
                }
            }
        });
        binding.rv.setLayoutManager(new LinearLayoutManager(mContext));
        binding.rv.setAdapter(shoppingCarAffirmAdapter);
    }


    @Override
    public void initData() {
        super.initData();
        //获取收货地址
        affirmOrderViewModel.receiveAddressList();
        //判断数据
        if(null != mShopMessageMoblieList && mShopMessageMoblieList.size() > 0){
            shoppingCarAffirmAdapter.Add(mShopMessageMoblieList);
        }
        if(null != mShopMessageMoblieList && mShopMessageMoblieList.size() > 0){
            /**
             * 计算价格
             */
            calculatePrice(mShopMessageMoblieList);
        }
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //没地址
        binding.tvNoAddress.setOnClickListener(this);
        //修改
        binding.ButtonModification.setOnClickListener(this);
        //立即购买
        binding.ButtonImmediatelyBuy.setOnClickListener(this);
        //获取收货地址
        affirmOrderViewModel.TheGoodsAddressMobileList.observe(this, new Observer<List<TheGoodsAddressMobile>>() {
            @Override
            public void onChanged(List<TheGoodsAddressMobile> theGoodsAddressMobiles) {
                if(null != theGoodsAddressMobiles && theGoodsAddressMobiles.size() > 0){
                    //没地址
                    binding.tvNoAddress.setVisibility(View.GONE);
                    //有地址
                    binding.llHaveAddress.setVisibility(View.VISIBLE);
                    for (TheGoodsAddressMobile theGoodsAddressMobile : theGoodsAddressMobiles){
                        if(theGoodsAddressMobile.getIs_default() == 1){
                            //当前选择的地址
                            affirmOrderViewModel.mTheGoodsAddressMobile.set(theGoodsAddressMobile);
                            //姓名手机号
                            binding.tvNameNumber.setText(theGoodsAddressMobile.getName() +"   " + theGoodsAddressMobile.getMobile());
                            //地址
                            binding.tvAddress.setText(theGoodsAddressMobile.getContent()+ "  " + theGoodsAddressMobile.getS_content());
                        }
                    }
                    if(null != affirmOrderViewModel.mTheGoodsAddressMobile.get()){
                        //没地址
                        binding.tvNoAddress.setVisibility(View.GONE);
                        //有地址
                        binding.llHaveAddress.setVisibility(View.VISIBLE);
                    }else {
                        //没地址
                        binding.tvNoAddress.setVisibility(View.VISIBLE);
                        //有地址
                        binding.llHaveAddress.setVisibility(View.GONE);
                    }
                }else {
                    //没地址
                    binding.tvNoAddress.setVisibility(View.VISIBLE);
                    //有地址
                    binding.llHaveAddress.setVisibility(View.GONE);
                }
            }
        });
        //添加订单
        affirmOrderViewModel.mCommonMobile.observe(this, new Observer<CommonMobile>() {
            @Override
            public void onChanged(CommonMobile commonMobile) {
                Map<String, Object> map = new HashMap<>();
                map.put("order_sn",commonMobile.getOrder_sn());
                map.put("pay_type",WeChatAlipay);
                if(WeChatAlipay == 0){//微信
                    affirmOrderViewModel.weChatpayOrder(map);
                }else if(WeChatAlipay == 1){//支付宝
                    affirmOrderViewModel.alipayPayOrder(map);
                }
            }
        });
        //微信付款信息
        affirmOrderViewModel.mWeChatPayMobile.observe(this, new Observer<WeChatPayMobile>() {
            @Override
            public void onChanged(WeChatPayMobile weChatPayMobile) {
                //调起微信
                PayUtils.getInstance(mContext).WeChatPay(weChatPayMobile);
            }
        });
        //支付宝付款信息
        affirmOrderViewModel.mAlipayString.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String AlipayPay) {
                //调起支付宝
                PayUtils.getInstance(mContext).AlipayPay(AlipayPay);
            }
        });

    }



    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.Button_modification://修改
                ARouter.getInstance().build(ARouterUtils.TheGoodsActivity)
                        .withSerializable("mTheGoodsAddressMobile", affirmOrderViewModel.mTheGoodsAddressMobile.get())
                        .withString("distinguish", "确认订单")
                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        .navigation(ShoppingCarAffirmActivity.this, 105);
                break;
            case R.id.tv_no_address://没地址
                ARouter.getInstance().build(ARouterUtils.TheGoodsActivity)
                        .withString("distinguish", "确认订单")
                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        .navigation(ShoppingCarAffirmActivity.this, 105);
                break;
            case R.id.Button_immediately_buy://立即购买
                if(null != payChooseDialog && !payChooseDialog.isShowing()){
                    payChooseDialog.show();
                    //价格

                    payChooseDialog.setPayMoneyContet(decimalFormat.format(mPrice) +"");
                    payChooseDialog.setAddItemOnClickListener(new AddItemOnClickListener() {
                        @Override
                        public void onSkipClicked(int position, Object mObject) {
                            WeChatAlipay = position;
                            Map<String, Object> map = new HashMap<>();
                            map.put("type",Cid);
                            map.put("cid",Cid);
                            map.put("price", decimalFormat.format(mPrice));
                            map.put("pay_type",position);
                            map.put("remark",binding.etNote.getText().toString());
                            map.put("send_id",affirmOrderViewModel.mTheGoodsAddressMobile.get().getId());
                            //店铺信息
                            List<GoodsShopMobile> goodsShopMobileList = new ArrayList<>();
                            for (ShopMessageMoblie shopMessageMoblie : mShopMessageMoblieList){
                                GoodsShopMobile goodsShopMobile = new GoodsShopMobile();
                                double specificationPrice = 0;
                                List<GoodsShopSPMobile> goodsShopSPMobileList = new ArrayList<>();
                                for (GoodsShopSPMobile goodsShopSPMobile : shopMessageMoblie.getProduct()){
                                    //添加规格
                                    goodsShopSPMobileList.add(goodsShopSPMobile);
                                    specificationPrice = specificationPrice + (goodsShopSPMobile.getNum() * goodsShopSPMobile.getProduct_spec_fee());
                                }
                                //店铺ID
                                goodsShopMobile.setSid(shopMessageMoblie.getId() +"");
                                //商品价格
                                 goodsShopMobile.setPrice(decimalFormat.format(specificationPrice) +"");
                                //商品数据
                                goodsShopMobile.setProduct(goodsShopSPMobileList);
                                goodsShopMobileList.add(goodsShopMobile);
                            }
                            map.put("shop",goodsShopMobileList);
                            LogUtils.d("商品信息" + new Gson().toJson(map));
                            affirmOrderViewModel.addOrder(map);
                            payChooseDialog.dismiss();
                        }
                    });
                }
                break;
        }
    }


    /**
     * 计算价格
     * @param shopMessageMoblieList
     */
    private void calculatePrice(List<ShopMessageMoblie> shopMessageMoblieList){
        int number = 0;
        double overallPrice = 0;
        for (ShopMessageMoblie shopMessageMoblie : shopMessageMoblieList){
            for (GoodsShopSPMobile goodsShopSPMobile : shopMessageMoblie.getProduct()){
                number =  number + goodsShopSPMobile.getNum();
                overallPrice = overallPrice + (goodsShopSPMobile.getNum() * goodsShopSPMobile.getProduct_spec_fee());
            }
        }
        mNumber = number;
        mPrice = overallPrice;
        binding.tvCommon.setText("共"+mNumber+"件");
        //价格
        binding.tvPrice.setText("¥" + decimalFormat.format(mPrice));
    }
}
